package com.powroznik.tracker.engine.data;

import java.util.Calendar;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class TrackerEngineDao {
	private SessionFactory sessionFactory;

	public List<Device> getAllDevices() {
		Criteria criteria = getCurrentSession().createCriteria(Device.class);
		return criteria.list();
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public Device getDeviceByCode1(String code1) {
		Criteria criteria = getCurrentSession().createCriteria(Device.class);
		criteria.add(Restrictions.eq("code1", code1));
		return (Device) criteria.uniqueResult();
	}

	public Device getDeviceById(Long id) {
		return (Device) getCurrentSession().get(Device.class, id);
	}

	public List<Device> getDevicesByAccount(Account account) {
		Query q = getCurrentSession()
				.createQuery(
						"FROM Device WHERE account = :account ORDER BY description DESC");
		q.setParameter("account", account);
		return q.list();
	}

	public Location getLastKnownLocation(Device device) {
		Query q = getCurrentSession().createQuery(
				"FROM Location WHERE device = :device ORDER BY time DESC");
		q.setParameter("device", device);
		q.setMaxResults(1);
		return (Location) q.uniqueResult();
	}

	public List<Location> getLastKnownLocations(Device device) {
		Query q = getCurrentSession()
				.createQuery(
						"FROM Location WHERE device = :device AND time > :time ORDER BY time DESC");
		q.setParameter("device", device);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -3);
		q.setParameter("time", cal.getTime());
		return q.list();
	}

	public User getUserByKey(String key) {
		Criteria criteria = getCurrentSession().createCriteria(User.class);
		criteria.add(Restrictions.eq("key", key));
		return (User) criteria.uniqueResult();
	}

	public void save(Object o) {
		getCurrentSession().saveOrUpdate(o);
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
